<?php

namespace app\admin\controller;

use app\common\entity\ResponseData;
use app\model\RoleRoutesRelation;
use app\model\Routes;
use app\model\Role;
use app\model\UserRoleRelation;
use think\Exception;

class Auth extends \app\admin\controller\AdminBase
{
    public function getRoutes()
    {
        $role_id = input('role_id');
        $roleRelation = UserRoleRelation::where(['user_id'=>$this->request->user->id, 'role_id' => $role_id, 'status'=>1])->find();
        if(!$roleRelation) {
            throw new Exception('您无此角色');
        }
        $relation = RoleRoutesRelation::where(['role_id' => $roleRelation->role_id, 'status'=>1])->find();
        $routes = Routes::when($roleRelation->role_id !== 1, fn ($query)=>$query->whereIn('id', $relation->routes_ids))->select();
        $routesArr = array_column($routes->toArray(), null,'id');
        foreach ($routesArr as $key => $item) {
            if ($item['pid'] == 0) {
                continue;
            }
            if (!isset($routesArr[$item['pid']]['children'])) {
                $routesArr[$item['pid']]['children'] = [];
            }
            $routesArr[$item['pid']]['children'][] = $item;
            unset($routesArr[$key]);
        }
        return ResponseData::success(array_values($routesArr));
    }

    public function getRoles()
    {
        $relation = UserRoleRelation::where(['user_id'=>$this->request->user->id])->select();
        $routes = Role::whereIn('id', array_column($relation->toArray(),'role_id'))->select();
        return ResponseData::success($routes);
    }
}